package com.yuxin.tongyi.lsll.sub;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yuxin.tongyi.lsll.R;
import com.yuxin.tongyi.lsll.common.Constants;
import com.yuxin.tongyi.lsll.common.TongyiTeaApplication;
import com.yuxin.tongyi.lsll.pojo.LifeInfo;
import com.yuxin.tongyi.lsll.pojo.LifeInfoList;
import com.yuxin.tongyi.lsll.pojo.LoginInfo;
import com.yuxin.tongyi.lsll.pojo.Student;
import com.yuxin.tongyi.lsll.pojo.StudentInfo;
import com.yuxin.tongyi.lsll.util.BorderTextView;
import com.yuxin.tongyi.lsll.util.HttpRequestUtil;
import com.yuxin.tongyi.lsll.util.PubUtil;

/**
 * @author ww
 * @date:2012-3-15 下午02:48:55
 * @Desc:
 * @version :
 * 
 */
public class DayLifePreviewActivity extends BaseActivity {
	private final static String TAG = "DayLifePreviewActivity";
	
	private Button btnSend, btnBack;
	private TextView tvClassName, tvDate;
	private TableLayout tlStudent, tlInfo;
	
	private ArrayList<LifeInfo> daylifeList;
	private ArrayList<Student> studentList;
	private int iGradeId;
	private String classId;
	private DayLifeThread mDayLifeThread;
	private MyHandler mHandler;
	private HttpRequestUtil request;
	private LoginInfo loginInfo;
	private String jsonStr;
	
	/** 表头行高默认为40px */
	private int headHeight = 40;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sub_daylife_preview);
		
		PubUtil.showProgressDialog(DayLifePreviewActivity.this, Constants.MSG_LOADING, Constants.MSG_WAIT);
		initView();
		initData();
		request = new HttpRequestUtil();
		mHandler = new MyHandler();
	}
	
	public void initView() {
		tvClassName = (TextView) findViewById(R.id.sub_daylifepre_tvclassname);
		tvDate = (TextView) findViewById(R.id.sub_daylifepre_tvDate);

		btnSend = (Button) findViewById(R.id.sub_daylifepre_btnSend);
		btnBack = (Button) findViewById(R.id.sub_daylifepre_btnBack);
		btnSend.setOnClickListener(new onBtnClickListener());
		btnBack.setOnClickListener(new onBtnClickListener());
		
		tlStudent = (TableLayout) findViewById(R.id.sub_daylifepre_student);
		tlInfo = (TableLayout) findViewById(R.id.sub_daylifepre_info);
	}

	public void initData() {
		Bundle bundle = getIntent().getExtras();
		if(bundle != null){
			tvClassName.setText(bundle.getString("classname"));
			tvDate.setText(bundle.getString("date"));
			iGradeId = Integer.parseInt(bundle.getString("gradeid"));
			classId = bundle.getString("classid");
			
			studentList = new ArrayList<Student>();
			studentList = (ArrayList<Student>) TongyiTeaApplication.getMap().get(Constants.GLOBAL_LIST_STUDENT);
			//studentList = (ArrayList<Student>) ((StudentInfo)bundle.getSerializable("studentlist")).getStudent();
			
			daylifeList = new ArrayList<LifeInfo>();
			daylifeList = (ArrayList<LifeInfo>) TongyiTeaApplication.getMap().get(Constants.GLOBAL_LIST_DAYLIFE);
			//daylifeList = (ArrayList<LifeInfo>) ((LifeInfoList) bundle.getSerializable("lifeInfoList")).getLifeInfo();
			//Log.i(TAG, daylifeList.size() + "--------1----------");
		}
		//创建fixColumn
		prepareFixColumn(tlStudent, studentList);
		//创建dataColumn
		prepareInfoColumn(tlInfo, studentList, daylifeList);
		
		try {
			loginInfo = (LoginInfo) TongyiTeaApplication.getMap().get(Constants.GLOBAL_LOGININFO);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		PubUtil.closeProgressDialog();
	}
	
	private void prepareFixColumn(TableLayout parent, ArrayList<Student> stuList){
		parent.removeAllViews(); 
		setFixColumnHead(parent, "姓名");
		setFixColumnData(parent, stuList);
	}
	
	//设置固定列表头
	private void setFixColumnHead(TableLayout parent, String title){
		TableRow titleRow = new TableRow(this);
		BorderTextView textView = getTextView(title, headHeight, Color.parseColor("#2A9366"));
		titleRow.addView(textView);
		parent.addView(titleRow);
	}
	
	//设置固定列数据
	private void setFixColumnData(TableLayout parent, ArrayList<Student> stulist){
		for(Student stu: stulist){
			TableRow titleRow = new TableRow(this);
			BorderTextView textView = getTextView(stu.getStudentName(), headHeight, Color.parseColor("#D2691E"));
			titleRow.addView(textView);
			parent.addView(titleRow);
		}
	}
	
	private void prepareInfoColumn(TableLayout parent, ArrayList<Student> stuList, ArrayList<LifeInfo> infoList){
		parent.removeAllViews(); 
		
		int[] title = new int[]{R.string.daylife_attendence, 
									  R.string.daylife_foodStatus,
									  R.string.daylife_foodCook,
									  R.string.daylife_sleepStatus,
									  R.string.daylife_driking,
									  R.string.daylife_motions,
									  R.string.daylife_homeWork,
									  R.string.daylife_edcution,
									  R.string.daylife_openair,
									  R.string.daylife_game,
									  R.string.daylife_health,
									  R.string.daylife_course,
									  R.string.daylife_remark};
		
		setInfoColumnData(parent, title, stuList, infoList);
	}
	
	
	private void setInfoColumnData(TableLayout parent, int[] title, ArrayList<Student> stuList, ArrayList<LifeInfo> infoList){
		//列数量
		int ColumnNum = title.length;
		int RowNum = stuList.size();
		
		//设置信息列表头
		BorderTextView textView;
		TableRow titleRow = new TableRow(this);
		for(int j=0; j<ColumnNum; j++){
			if(iGradeId>4 && (title[j]==R.string.daylife_motions || title[j]==R.string.daylife_driking)){
				continue;
			}else if(iGradeId>0 && iGradeId<4 && title[j]==R.string.daylife_homeWork){
				continue;
			}else if(title[j]==R.string.daylife_remark){
				continue;
			}
			textView = getTextView(getResources().getString(title[j]), headHeight, Color.parseColor("#2A9366"));
			titleRow.addView(textView);
		}
		parent.addView(titleRow);
		
		for(Student stu: stuList){
			//设置信息列数据
			TableRow titleRow1 = new TableRow(this);
			for(LifeInfo li: infoList){
				if(stu.getStudentId().equals(li.getStudentId())){
					textView = getTextView(li.getAttendence(), headHeight, Color.parseColor("#D2691E"));
					titleRow1.addView(textView);
					textView = getTextView(li.getFoodStatus(), headHeight, Color.parseColor("#D2691E"));
					titleRow1.addView(textView);
					textView = getTextView(li.getFoodCook(), headHeight, Color.parseColor("#D2691E"));
					titleRow1.addView(textView);
					textView = getTextView(li.getSleepStatus(), headHeight, Color.parseColor("#D2691E"));
					titleRow1.addView(textView);
					
					if(iGradeId>=4){
						textView = getTextView(li.getHomeWork(), headHeight, Color.parseColor("#D2691E"));
						titleRow1.addView(textView);
					}else if(iGradeId>0 && iGradeId<4){
						textView = getTextView(li.getDriking(), headHeight, Color.parseColor("#D2691E"));
						titleRow1.addView(textView);
						textView = getTextView(li.getMotions(), headHeight, Color.parseColor("#D2691E"));
						titleRow1.addView(textView);
					}
					
					textView = getTextView(li.getEdcution(), headHeight, Color.parseColor("#D2691E"));
					titleRow1.addView(textView);
					textView = getTextView(li.getOpenair(), headHeight, Color.parseColor("#D2691E"));
					titleRow1.addView(textView);
					textView = getTextView(li.getGame(), headHeight, Color.parseColor("#D2691E"));
					titleRow1.addView(textView);
					textView = getTextView(li.getHealth(), headHeight, Color.parseColor("#D2691E"));
					titleRow1.addView(textView);
					textView = getTextView(li.getCourse(), headHeight, Color.parseColor("#D2691E"));
					titleRow1.addView(textView);
//					textView = getTextView(li.getRemark(), headHeight, Color.parseColor("#D2691E"));
//					titleRow1.addView(textView);
					parent.addView(titleRow1);
				}
				
			}
		}
	}
	
	private class onBtnClickListener implements OnClickListener {
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.sub_daylifepre_btnSend:
				PubUtil.showProgressDialog(DayLifePreviewActivity.this, Constants.MSG_SENDING, Constants.MSG_WAIT);
				jsonStr = GetJsonDataToString(daylifeList);
				//Log.i(TAG, daylifeList.size() + "--------2----------");
				
				mDayLifeThread = new DayLifeThread();
				new Thread(mDayLifeThread).start();
				break;
			case R.id.sub_daylifepre_btnBack:
				finish();
				break;
			}
		}
	}
	
private class DayLifeThread implements Runnable {
		
		@Override
		public void run() {
			boolean requestFlag = false;
			requestFlag = request.requestSendDayLife(loginInfo.getLoginName(), loginInfo.getPassword(), classId,  jsonStr);
			
			String status = request.getStatus();
			Message msg = mHandler.obtainMessage();
			try {
				if (requestFlag) {
					if ("0".equals(status)) {
						msg.what = Constants.TH_DAYLIFE_SEND;
					} else {
						msg.what = Constants.TH_DATA_ERROR;
					}
				} else { // 访问服务器失败
					msg.what = Constants.TH_SERVER_OFF;
				}
				mHandler.sendMessage(msg);
			} catch (Exception e) {
				msg.what = Constants.TH_SERVER_OFF;
				mHandler.sendMessage(msg);
			}
		}
	}

	private class MyHandler extends Handler {
	
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle bundle = msg.getData();
			switch (msg.what) {
			case Constants.TH_DAYLIFE_SEND:
				PubUtil.closeProgressDialog();
				PubUtil.showDialog(DayLifePreviewActivity.this, "提示","发送成功",null,false);
				break;
			case Constants.TH_DATA_ERROR:
				PubUtil.closeProgressDialog();
	        	PubUtil.showToast(DayLifePreviewActivity.this, Constants.MSG_DATA_ERROR);
				break;
			case Constants.TH_SERVER_OFF:
				PubUtil.closeProgressDialog();
	        	PubUtil.showToast(DayLifePreviewActivity.this, Constants.MSG_SERVER_OFF);
				break;
			}
		}
	}

	/**
	 * 获取文本框
	 * @param text		     文本内容
	 * @param borderColor 边框颜色
	 * @param height 	     文本框高度
	 * @param align		     对齐方式
	 * @param fontColor	    字体颜色
	 * @return
	 */
	private BorderTextView getTextView(String text,int height, int textColor) {
		BorderTextView textView = new BorderTextView(this,Color.parseColor("#0082AD"));
		textView.setText(Html.fromHtml(text));
		textView.setGravity(Gravity.CENTER);
		textView.setHeight(height);
		textView.setTextColor(textColor);
		textView.setPadding(3, 0, 3, 0);
		return textView;
	}
	
	private String GetJsonDataToString(ArrayList<LifeInfo> list){
		Gson gson = new Gson();
		Type type = new TypeToken<List<LifeInfo>>(){}.getType();
		return gson.toJson(list, type);
		
	}
}
